<?php

namespace app\admin\controller;

use app\model\BizTagModel;
use app\model\BizTagRelationModel;
use support\Request;
use support\Response;

/**
 * 商家标签管理控制器
 * 
 * 用于管理商家标签的增删改查操作
 * 
 * @package app\admin\controller
 */
class BizTagController
{
    /**
     * 获取标签列表
     * 
     * @param Request $request 请求对象
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $page = (int) $request->get('current', 1);
            $pageSize = (int) $request->get('pageSize', 10);
            $name = $request->get('name', '');
            
            $query = BizTagModel::query();
            
            // 搜索条件
            if (!empty($name)) {
                $query->where('name', 'like', "%{$name}%");
            }
            
            // 分页查询
            $total = $query->count();
            $list = $query->orderBy('id', 'desc')
                         ->offset(($page - 1) * $pageSize)
                         ->limit($pageSize)
                         ->get()
                         ->toArray();
            
            // 为每个标签添加关联商家数
            foreach ($list as &$item) {
                $item['biz_count'] = BizTagRelationModel::where('tag_id', $item['id'])->count();
            }
            
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total,
                    'current' => $page,
                    'pageSize' => $pageSize
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
    
    /**
     * 获取所有标签（不分页）
     * 
     * @param Request $request 请求对象
     * @return Response
     */
    public function all(Request $request): Response
    {
        try {
            $list = BizTagModel::query()
                ->orderBy('id', 'desc')
                ->get()
                ->toArray();
            
            return json([
                'data' => $list,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
    
    /**
     * 添加标签
     * 
     * @param Request $request 请求对象
     * @return Response
     */
    public function store(Request $request): Response
    {
        try {
            $name = $request->post('name');
            $description = $request->post('description', '');
            
            // 参数验证
            if (empty($name)) {
                throw new \Exception('标签名称不能为空');
            }
            
            // 检查标签名称是否已存在
            $exists = BizTagModel::where('name', $name)->exists();
            if ($exists) {
                throw new \Exception('标签名称已存在');
            }
            
            // 创建标签
            $tag = new BizTagModel();
            $tag->name = $name;
            $tag->description = $description;
            $tag->created_at = time();
            $tag->updated_at = time();
            
            if (!$tag->save()) {
                throw new \Exception('创建标签失败');
            }
            
            return json([
                'data' => $tag->toArray(),
                'msg' => '创建成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
    
    /**
     * 更新标签
     * 
     * @param Request $request 请求对象
     * @return Response
     */
    public function update(Request $request): Response
    {
        try {
            $id = (int) $request->post('id');
            $name = $request->post('name');
            $description = $request->post('description', '');
            
            // 参数验证
            if (empty($id)) {
                throw new \Exception('标签ID不能为空');
            }
            
            if (empty($name)) {
                throw new \Exception('标签名称不能为空');
            }
            
            // 查找标签
            $tag = BizTagModel::find($id);
            if (!$tag) {
                throw new \Exception('标签不存在');
            }
            
            // 检查标签名称是否已存在（排除当前标签）
            $exists = BizTagModel::where('name', $name)->where('id', '!=', $id)->exists();
            if ($exists) {
                throw new \Exception('标签名称已存在');
            }
            
            // 更新标签
            $tag->name = $name;
            $tag->description = $description;
            $tag->updated_at = time();
            
            if (!$tag->save()) {
                throw new \Exception('更新标签失败');
            }
            
            return json([
                'data' => $tag->toArray(),
                'msg' => '更新成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
    
    /**
     * 删除标签
     * 
     * @param Request $request 请求对象
     * @param int $id 标签ID
     * @return Response
     */
    public function destroy(Request $request): Response
    {
        try {
            $id = (int) $request->post('id');
            // 查找标签
            $tag = BizTagModel::find($id);
            if (!$tag) {
                throw new \Exception('标签不存在');
            }
            
            // 删除标签
            if (!$tag->delete()) {
                throw new \Exception('删除标签失败');
            }
            
            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
} 